package bll

import (
	"context"
	"maya-service/store/mysql"

	"maya-service/model"
	"maya-service/model/entity"
	"maya-service/model/mapping"
	"maya-service/store"
	"time"
)

type quanxiRecord struct {
	iQuanxiRecord store.IQuanxiRecord
}

var QuanxiRecord = &quanxiRecord{
	iQuanxiRecord: mysql.QuanxiRecord,
}

func init() {
	Register(QuanxiRecord)
}

func (a *quanxiRecord) init() func() {
	return func() {}
}

// Create
func (a *quanxiRecord) Create(ctx context.Context, in *model.QuanxiRecordCreateRequest) error {
	var (
		err error
	)
	c := buildQuanxiRecord(in)
	_, err = a.iQuanxiRecord.Create(ctx, c)
	return err
}

// Update
func (a *quanxiRecord) Update(ctx context.Context, in *model.QuanxiRecordUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	if in.UserId != nil {
		dict["user_id"] = in.UserId
	}

	if in.Status != nil {
		dict["status"] = in.Status
	}

	if in.AnswerName != nil {
		dict["answer_name"] = in.AnswerName
	}

	if in.Select != nil {
		dict["select"] = in.Select
	}

	if in.QuestionId != nil {
		dict["question_id"] = in.QuestionId
	}

	if in.CreatedAt != nil {
		dict["created_at"] = in.CreatedAt
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	// do other update here
	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt
	return a.iQuanxiRecord.Update(ctx, in.Id, dict)
}

// Delete
func (a *quanxiRecord) Delete(ctx context.Context, in *model.QuanxiRecordDeleteRequest) error {
	return a.iQuanxiRecord.Delete(ctx, in.Id)
}

func (a *quanxiRecord) Count(ctx context.Context, userId string) int64 {
	notRead := 0
	list, err := a.List(ctx, &model.QuanxiRecordListRequest{
		UserId: &userId,
		Status: &notRead,
		Index:  1,
		Size:   10000,
	})
	if err != nil {
		return 0
	}

	return int64(list.Total)
}

// List
func (a *quanxiRecord) List(ctx context.Context, in *model.QuanxiRecordListRequest) (*model.QuanxiRecordListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.QuanxiRecord
		out   = &model.QuanxiRecordListResponse{}
	)

	if total, list, err = a.iQuanxiRecord.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = mapping.QuanxiRecordsEntityToDto(list)

	return out, nil
}

// Find
func (a *quanxiRecord) Find(ctx context.Context, in *model.QuanxiRecordInfoRequest) (*model.QuanxiRecordInfo, error) {
	var (
		err  error
		data *entity.QuanxiRecord
		out  = &model.QuanxiRecordInfo{}
	)

	if data, err = a.iQuanxiRecord.Find(ctx, in); err != nil {
		return nil, err
	}

	out = mapping.QuanxiRecordEntityToDto(data)
	return out, nil
}

// buildQuanxiRecord build entity
func buildQuanxiRecord(in *model.QuanxiRecordCreateRequest) *entity.QuanxiRecord {

	ety := &entity.QuanxiRecord{}

	ety.UserId = in.UserId

	ety.Status = in.Status

	ety.AnswerName = in.AnswerName

	ety.AnswerType = in.AnswerType

	ety.Select = in.Select

	ety.QuestionId = in.QuestionId

	ety.CreatedAt = time.Now().Unix()

	ety.UpdatedAt = in.UpdatedAt

	return ety
}
